package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.mapper.CompetitionMapper;
import com.example.demo.myModel.entity.Competition;
import com.example.demo.service.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CompetitionScheduleService {

    @Resource
    private CompetitionMapper competitionMapper;

    @Resource
    private NotificationService notificationService;

    /**
     * 每天凌晨1点执行竞赛状态更新
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateCompetitionStatus() {
        try {
            LocalDateTime now = LocalDateTime.now();
            UpdateWrapper<Competition> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("state", 0)
                        .lt("eTime", now);
            competitionMapper.update(null, updateWrapper);
            log.info("竞赛状态更新完成");
        } catch (Exception e) {
            log.error("竞赛状态更新失败", e);
        }
    }

    /**
     * 每天上午10点执行报名提醒
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void sendSignUpReminder() {
        try {
            LocalDateTime deadline = LocalDateTime.now().plusDays(1);
            QueryWrapper<Competition> queryWrapper = new QueryWrapper<>();
            queryWrapper.between("sETime", LocalDateTime.now(), deadline);
            
            List<Competition> competitions = competitionMapper.selectList(queryWrapper);
            
            for (Competition competition : competitions) {
                String message = String.format("竞赛《%s》报名即将截止，请及时报名！", 
                    competition.getHeadText());
                // TODO: 实现发送提醒通知的具体逻辑
                log.info("发送报名提醒: {}", message);
            }
        } catch (Exception e) {
            log.error("发送报名提醒失败", e);
        }
    }
} 